import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { Link } from 'react-router'
import { Table, Spin, Form, Row, Col, Input, Button, Select, TreeSelect, DatePicker, Checkbox, message, Dropdown, Menu, Icon, Upload, notification } from 'antd'
import _ from 'lodash'
import moment from 'moment'

import Ajax from 'lib/Ajax'
import { addConfig } from 'actions/config'
import { getNewTreeData, findRowData, getNameByCode, confirmDelete, getYear, getNameByState, download, tableWidth, statistics, backUrl } from 'lib/fun'
import SubmitingUser from './components/submitingUser'
import ExportModule from './components/exportModule'
import FilterModule from './components/filterSummary'
import BarInfo from 'components/barInfo'

const FormItem = Form.Item;
const SelectTreeNode = TreeSelect.TreeNode;
const { RangePicker } = DatePicker;
const Option = Select.Option;

class ModuleName extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      data: [],
      projectList: [],
      visible: false,
      editType: "",
      rowdata: "",
      showBar: false,
      barId: "",
      typeId: "",
    }
    this.current = 1;   //当前第几页
    this.total = 0;   //总共多少页
    this.pageSize = 10;   //每页多少行
    this.search = {};
  }

  componentDidMount(){
    const { config, addConfig } = this.props;
    // load 项目列表
    this.loadProject();
    // citizen_info_type_code  人员分类没有找着
    this.loadData();
    if(!config.payObjCode){
      // 发放对象
      addConfig('payObjCode',10);
    }
    if(!config.payCycleCode){
      // 发放周期
      addConfig('payCycleCode',9);
    }
  }

  componentWillUnmount(){
    notification.destroy();
  }

  pageOnChange = (page)=>{
    this.current = page;
    this.loadData();
  }

  showSizeChange = (current, pageSize)=>{
    var page = Math.ceil(((this.current-1)*this.pageSize+1)/pageSize);
    this.pageSize = pageSize;
    this.current = page;
    this.loadData();
  }

  loadProject = ()=>{
    var self = this;
    Ajax({
      url: '/project/list',
      data: {
        perPage: 10000,   //每页数量
      },
      success: function(data){
        self.setState({
          projectList: data.list
        });
      },
      error: function(error){
        message.error(error);
      }
    });
  }

  loadData = () => {
    var self = this;
    self.setState({
      loading: true
    });
    const {  } = this.search;
    Ajax({
      url: '/projectRegister/financeAuditoredSummaryBatchList',
      data: Object.assign({}, this.search, {
        currentPage: self.current, 
        perPage: self.pageSize
      }),
      success: function(data){
        self.total = data.totalCount;
        self.setState({
          loading: false,
          data: data.list
        });
      },
      error: function(error){
        self.setState({
          loading: false
        });
        message.error(error);
      }
    });
  }

  handleFilter = (option)=>{
    if(!_.isEqual(option, this.search)){
      this.search = option;
      this.loadData();
    }
  }
  
  // 提交上报
  approvalSubmit = (auditorType, summaryId)=>{
    var self = this;
    if(auditorType == 1){
      Ajax({
        url: '/projectRegister/financeCreatedFile',
        data: {
          summaryId
        },
        success: function(data){
          var find = _.find(self.state.data, function(d) {
            return d.summaryId == summaryId
          });
          find.state = 110;
          self.setState({
            data: self.state.data
          });
          // self.loadData()
        },
        error: function(error){
          message.error(error);
        }
      });
    }else{
      Ajax({
        url: '/projectRegister/financeDownFile',
        data: {
         summaryId
        },
        success: function(data){
          download(data);
          // var find = _.find(self.state.data, function(d) {
          //   return d.summaryId == summaryId
          // });
          // find.state = 120;
          // self.setState({
          //   data: self.state.data
          // });
          self.loadData()
        },
        error: function(error){
          message.error(error);
        }
      });
    }
  }

  // 导入
  onExport = (b)=>{
    this.setState({ 
      showBar: false 
    })
    b&&this.loadData()
  }
  // 回执
  upload = (id)=>{
    this.setState({ 
      // visible: true,
      rowdata: id
    })
  }

  operate = (type, row, num)=>{
    if(num&&num>0){
      this.setState({
        visible2: true,
        editType: type,
        rowdata: row.summaryId
      });
    }
  }

  render() {
    const self = this;

    var data = {
      summaryId: this.state.rowdata
    }

    const props = {
      name: 'file',
      multiple: false,
      showUploadList: false,
      action: backUrl("/projectRegister/financeUploadReceipt"),
      data: data,
      onChange(info) {
        const status = info.file.status;
        if (status == 'uploading') {
          self.setState({
            showBar: true
          });
        }
        if (status === 'done') {
          var result = info.file.response;
          // &&result.data.successCount&&result.data.successCount>0
          if(result.status == 1&&result.data){
            const data = result.data
            self.setState({
              showBar: true,
              barId: data.barId,
              typeId: data.typeId,
            });
          }else{
            notification.error({
              message: '文件上传失败',
              description: result.msg||"未知失败原因",
              duration: 60,
            });
            self.setState({
              showBar: false
            });
          }
        } else if (status === 'error') {
          message.error("文件上传失败");
          self.setState({
            showBar: false
          });
        }
      },
      beforeUpload(file) {
        if((new RegExp(self.state.rowdata)).test(file.name)){
          return true
        }else{
          message.info("选择文件与批次不符");
          return false
        }
      }
    };

    const { config, common } = this.props;
    const columns = [{
      title: '汇总批次ID',
      dataIndex: 'summaryId'
    }, {
      title: '项目编号',
      dataIndex: 'projectId'
    }, {
      title: '项目名称',
      dataIndex: 'projectName'
    }, {
      title: '补贴年度',
      dataIndex: 'year'
    }, {
      title: '发放周期',
      dataIndex: 'payCycleCode',
      render: (text, record) => (<span>{ getNameByCode(config, 'payCycleCode', text) }</span>)
    }, {
      title: '补贴次数',
      dataIndex: 'subsidyCount'
    }, {
      title: '区划名称',
      dataIndex: 'areaName'
    }, {
      title: '总登记成功人数',
      dataIndex: 'totalCount',
      render: (text, record) => (<span><a href="javascript:;" title="查看详情" onClick={this.operate.bind(this, 'total', record, text)}>{text?text:0}</a></span>)
    }, {
      title: '成功人数',
      dataIndex: 'successCount',
      render: (text, record) => (<span><a href="javascript:;" title="查看详情" onClick={this.operate.bind(this, 'success', record, text)}>{text?text:0}</a></span>)
    }, {
      title: '成功金额',
      dataIndex: 'successMoney'
    }, {
      title: '失败人数',
      dataIndex: 'failCount',
      render: (text, record) => (<span><a href="javascript:;" title="查看详情" onClick={this.operate.bind(this, 'fail', record, text)}>{text?text:0}</a></span>)
    }, {
      title: '状态',
      dataIndex: 'state',
      fixed: 'right',
      render: (text, record) => (<span>{ getNameByState(common, "projectRegisterBatchEn", text) }</span>)
    }, {
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
      render: (text, record) => <Dropdown overlay={
          <Menu>
            {
              record.state < 110?(<Menu.Item>
              <a onClick={this.approvalSubmit.bind(this, 1, record.summaryId)} href="javascript:;">生成代发文件</a>
            </Menu.Item>):null
            }
            {
              record.state >= 110?(<Menu.Item>
                <a onClick={this.approvalSubmit.bind(this, 2, record.summaryId)} href="javascript:;">下载代发文件</a>
              </Menu.Item>):null
            }
            {
              record.state >= 120?(<Menu.Item>
                <Upload {...props}>
                  <a href="javascript:;" onClick={this.upload.bind(this, record.summaryId)} style={{color: '#666'}}>上传回执</a>
                </Upload>
              </Menu.Item>):null
            }
          </Menu>
      }>
        <a className="ant-dropdown-link" href="javascript:;">
          操作 <Icon type="down" />
        </a>
      </Dropdown>
    }];

    var width = tableWidth(columns);

    var pagination = {
      current: this.current,
      total: this.total,
      pageSize: this.pageSize,
      onChange: this.pageOnChange,
      showSizeChanger: true,
      onShowSizeChange: this.showSizeChange,
      showTotal: total => `总共 ${total} 条`
    };

    return (
      <div className="area projectRegister">
        <FilterModule 
          handleFilter={ this.handleFilter }
          projectList={ this.state.projectList }
          state={90}
        />
        <div className="area-con">
          <Table 
            columns={columns}
            dataSource={this.state.data}
            pagination={pagination}
            rowKey="summaryId"
            footer={ ()=> statistics(this.state.data) }
            scroll={{ x: width, y: false }}
            loading={ this.state.loading }
          />
          <ExportModule 
            visible={this.state.visible}
            onClose={this.onExport}
            url="/projectRegister/financeUploadReceipt"
            data={data}
            title="上传银行回执"
          />
          <SubmitingUser
            visible={this.state.visible2}
            onClose={()=>this.setState({ visible2: false })}
            type={ this.state.editType }
            batchId = { this.state.rowdata }
            see={true}
            isSummary={true}
            failDown={true}
            successDown={ true }
          />
          <BarInfo
            visible={this.state.showBar}
            barId={this.state.barId}
            typeId={this.state.typeId}
            onClose={this.onExport}
            successTitle="发放成功"
            failTitle="发放失败"
          />
        </div>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    config: state.config,
    common: state.common
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({ addConfig }, dispatch)
}

module.exports = connect(mapStateToProps,mapDispatchToProps)(ModuleName)